package com.tools.genxsd.store.factory;

import cn.hutool.core.text.CharSequenceUtil;
import com.tools.genxsd.entity.XsdBaseType;
import com.tools.genxsd.entity.type.XsdDecimalType;
import com.tools.genxsd.entity.type.XsdStringType;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static cn.hutool.core.text.StrPool.COLON;
import static cn.hutool.core.text.StrPool.LF;
import static com.tools.genxsd.constant.BaseTypeConstant.BASE_TYPE_DECIMAL;
import static com.tools.genxsd.constant.BaseTypeConstant.BASE_TYPE_STRING;
import static com.tools.genxsd.constant.SysConstant.*;

/**
 * @author: zhoubin
 * @date: 2022/11/17
 */
public class SimpTypeFactory {

    public static XsdBaseType createType(String name, String type, String val) {

        XsdBaseType baseType = null;
        switch (type) {
            case BASE_TYPE_STRING:
                baseType = packStringType(name, val);
                break;
            case BASE_TYPE_DECIMAL:
                baseType = packDecimalType(name, val);
                break;
            default:
        }

        return baseType;
    }

    private static XsdBaseType packDecimalType(String name, String val) {
        XsdDecimalType decimalType = XsdDecimalType.builder().name(name).baseType(BASE_TYPE_DECIMAL).build();

        String[] split = val.split(LF);
        for (String s : split) {
            String[] keyVal = s.split(COLON);

            if (Objects.equals(keyVal[0], FRACTION_DIGITS)) {
                decimalType.setFractionDigits(keyVal[1]);
            } else if (Objects.equals(keyVal[0], TOTAL_DIGITS)) {
                decimalType.setTotalDigits(keyVal[1]);
            } else if (Objects.equals(keyVal[0], MIN_INCLUSIVE)) {
                decimalType.setMinInclusive(keyVal[1]);
            }
        }

        return decimalType;
    }

    public static XsdStringType packStringType(String typeName, String typeDescribe) {
        XsdStringType tempType = new XsdStringType(typeName, BASE_TYPE_STRING);

        if (CharSequenceUtil.isBlank(typeDescribe)
                || (!typeDescribe.contains(LF) && !typeDescribe.startsWith(PATTERN))) {
            return tempType;
        }

        if (typeDescribe.startsWith(PATTERN)) {
            tempType.setPattern(typeDescribe.substring(typeDescribe.indexOf(COLON) + 1).trim());

            return tempType;
        }

        List<String> enumList = new ArrayList<>();
        tempType.setEnumList(enumList);

        String[] split = typeDescribe.split(LF);
        for (String s : split) {

            if (s.contains(CHINA_COLON)) {
                enumList.add(s.split(CHINA_COLON)[0]);
                continue;
            }

            if (s.contains(COLON)) {
                enumList.add(s.split(COLON)[0]);
                continue;
            }

            enumList.add(s.split(SPACE)[0]);
        }

        return tempType;
    }
}
